<template>
    <el-container style="border: solid 1px #5d7db3; margin: 35px;">
        <el-header style="background-color: #5d7db3; display: flex; align-items: center; margin-bottom: 20px;">
            <div class="title">
                <span>专题管理</span>
            </div>
        </el-header>
        <div>
            <el-main>
                <el-row :gutter="40">
                    <el-col :span="4">
                        <!-- 添加专题按钮 -->
                        <el-button style="background-color: #5D7DB3; border:none;" class="add" type="success"
                            icon="el-icon-plus" @click="showAddDialog">添加</el-button>
                    </el-col>
                </el-row>
                <el-table :data="currentThematicTableData" border strip style="width: 100%" @row-click="handleRowClick"
                    :row-class-time="highlightRow">
                    <el-table-column prop="name" label="专题"></el-table-column>
                    <el-table-column prop="specialDate" label="日期"></el-table-column>
                    <el-table-column prop="departmentId" label="所属部门"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="success" @click="handleEdit(scope.row)">编辑<i
                                    class="el-icon-edit"></i></el-button>
                            <el-button type="danger" @click="handleDelete(scope.row)">删除<i
                                    class="el-icon-remove-outline"></i></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
            <!-- 添加专题的弹窗 -->
            <el-dialog title="添加专题" :visible.sync="addDialog" width="30%" @close="resetForm">
                <el-form :model="form" ref="form" :rules="yourFormRules" label-width="100px">
                    <el-form-item label="专题" prop="name">
                        <el-input v-model="form.name" placeholder="请输入专题内容"></el-input>
                    </el-form-item>
                    <el-form-item label="日期" prop="specialDate">
                        <div class="block">
                            <el-date-picker v-model="form.specialDate" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </div>
                    </el-form-item>
                    <el-form-item label="部门" prop="departmentId">
                        <el-select v-model="form.departmentId" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click=" addDialog = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑行的弹窗 -->
            <el-dialog title="添加专题" :visible.sync="showDialog" width="30%">
                <el-form :model="yourFormModel" :rules="yourFormRules" label-width="100px">
                    <el-form-item label="专题" prop="name">
                        <el-input v-model="yourFormModel.name" placeholder="请输入专题内容"></el-input>
                    </el-form-item>
                    <el-form-item label="日期" prop="specialDate">
                        <div class="block">
                            <el-date-picker v-model="yourFormModel.specialDate" type="date" placeholder="选择日期"
                                format="yyyy-MM-dd">
                            </el-date-picker>
                        </div>
                    </el-form-item>
                    <el-form-item label="部门" prop="departmentId">
                        <el-select v-model="yourFormModel.departmentId" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button @click=" showDialog = false">取消</el-button>
                </div>
            </el-dialog>
        </div>
        <el-footer>
            <el-pagination class="ThematicPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="thematicTableData.length">
            </el-pagination>
        </el-footer>
    </el-container>

</template>
<script>
import axios from 'axios';
export default {
    data() {
        return {
            thematicTableData: [],
            options: [{
                value: '选项1',
                label: '1'
            }, {
                value: '选项2',
                label: '1'
            }, {
                value: '选项3',
                label: '1'
            }],
            currentPage: 1,
            pageSize: 10,
            selectedRow: null,
            addDialog: false,
            showDialog: false,
            form: {
                name: '',
                specialDate: '',
                departmentId: ''
            },
            yourFormModel: {
                name: '',
                specialDate: '',
                departmentId: ''
            },
            yourFormRules: {
                name: [
                    { required: true, message: '请输入专题内容', trigger: 'blur' },
                ],
                specialDate: [
                    { required: true, message: '请选择专题时间', trigger: 'change' }
                ],
                departmentId: [
                    { required: true, message: '请输入部门', trigger: 'blur' },
                ],
            },
        };
    },
    computed: {
        // 计算当前页的数据
        currentThematicTableData() {
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            return this.thematicTableData.slice(startIndex, endIndex);
        }
    },
    created() {
        this.fetchThematic();
    },
    methods: {
        // 分页大小变化时的回调
        handleSizeChange(val) {
            this.pageSize = val;
        },
        // 当前页变化时的回调
        handleCurrentChange(val) {
            this.currentPage = val;
        },
        // 选中变颜色
        handleRowClick(row) {
            this.selectedRow = row;
        },
        highlightRow(row) {
            return row === this.selectedRow ? 'highlight' : '';
        },
        //获取全部数据
        fetchThematic() {
            axios.get('/zhuantis/getAll')
                .then(response => {
                    // 检查响应数据的结构
                    if (Array.isArray(response.data.data)) {
                        this.thematicTableData = response.data.data;
                    } else {
                        console.error('Invalid response format:', response.data);
                    }
                })
                .catch(error => {
                    console.error('Error fetching departments:', error);
                    this.thematicTableData = [];
                });
        },
        //添加按钮
        showAddDialog() {
            this.addDialog = true;
        },
        resetForm() {
            this.$refs.form.resetFields();
        },
        submitForm() {
            console.log('Form:', this.form);
            this.$refs.form.validate(valid => {
                if (valid) {
                    const thematicAddData = {
                        name: this.form.name,
                        specialDate: this.form.specialDate,
                        departmentId: this.form.departmentId
                    };
                    axios.post('/zhuantis/add', thematicAddData)
                        .then(response => {
                            console.log('Data successfully sent to backend:', response);
                            if (response && response.status === 200) {
                                this.thematicTableData.push({
                                    name: this.form.name,
                                    specialDate: this.form.specialDate,
                                    departmentId: this.form.departmentId
                                });
                                this.$message({
                                    type: "success",
                                    message: '添加成功'
                                });
                                this.fetchThematic();
                                this.totalItemNotice = this.thematicTableData.length;
                                this.currentPageNotice = this.totalPages;
                                this.addDialog = false;
                                this.$refs.form.resetFields();
                            } else {
                                console.error('Error sending data to backend:', response);
                                this.$message('添加功能出现异常');
                            }
                        })
                        .catch(error => {
                            console.error('Error sending data to backend:', error);
                            this.$message('添加功能出现异常');
                        });
                }
            });
        },
        //编辑行
        handleEdit(row) {
            this.showDialog = true;
            this.yourFormModel.name = row.name;
            this.yourFormModel.specialDate = row.specialDate;
            this.yourFormModel.departmentId = row.departmentId;
        },
        save() {
            const rowIndex = this.thematicTableData.indexOf(this.selectedRow);
            this.thematicTableData[rowIndex].name = this.yourFormModel.name;
            this.thematicTableData[rowIndex].specialDate = this.yourFormModel.
                specialDate;
            this.thematicTableData[rowIndex].departmentId = this.yourFormModel.departmentId;
            // 向后端发送更新请求
            axios.put(`/zhuantis/update/${this.selectedRow.specialId}`, {
                name: this.yourFormModel.name,
                specialDate: this.yourFormModel.specialDate,
                departmentId: this.yourFormModel.departmentId
            })
                .then(() => {
                    this.showDialog = false;
                    this.fetchThematic();
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    });
                })
                .catch(error => {
                    console.error('Error updating department:', error);
                    this.$message.error('保存专题数据时出现错误');
                });
        },
        //删除行
        handleDelete(row) {
            this.$confirm('此操作将删除该专题, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 向后端发送删除请求
                axios.delete(`/zhuantis/delete/${row.specialId}`)
                    .then(() => {
                        // 从前端数组中删除部门数据
                        const index = this.thematicTableData.indexOf(row);
                        if (index >= 0 && index < this.thematicTableData.length) {
                            this.thematicTableData.splice(index, 1);
                            this.fetchThematic();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting department:', error);
                        this.$message.error('删除专题出现错误');
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    }
}
</script>
<style scoped>
.title {
    font-size: 30px;
    font-family: '500';
    color: aliceblue;
}

.highlight {
    background-color: lightblue;
}

.ThematicPage {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
